import React from "react";
import {connect} from "react-redux";
import action from "../store/action";
import { Modal, Form, Select, Card, Checkbox, Button, Input } from 'antd';
import {modifyFunctionApi, addFunctionApi, delFunctionApi, listFunArgApi} from "../api/projectConfig";
import {message} from "antd/lib/index";

const { TextArea } = Input;
const FormItem = Form.Item;
const Option = Select.Option;
const confirm = Modal.confirm;

class ControllerFun extends React.Component {

    funId;

    state = { returnShow: 'Void', argShow: 'null', funInfo:{} }
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        let {funInfo} = this.props;
        this.funId = funInfo.id;
        this.state.funInfo = funInfo;

        console.log(this.state.funInfo);

        this.state.returnShow = funInfo.returnShow ? funInfo.returnShow : 'Void'
        this.showParmas();
    }

    saveFuncInfo = (e) => {
        e.preventDefault();

        let {funInfo} = this.props

        let formData = this.props.form.getFieldsValue()
        formData.cid = funInfo.cid; // controller id

        if(this.funId) {
            formData.id = this.funId
            modifyFunctionApi(formData)
        } else {
            let ret = addFunctionApi(formData)
            ret.then((res) => {
                this.funId = res.data.data.id;
                this.state.funInfo.id = this.funId;
                this.props.onUpdateFun();
            })
        }

        message.success('保存成功！')

    }

    // 显示设置的参数
    showParmas = ()=>{

        if(this.state.funInfo.id) {
            listFunArgApi(this.state.funInfo.id).then(res=>{
                let args = res.data.data
                var showArr = [];
                args.forEach(value => {
                    showArr.push(value.argTypeName + ' ' + value.name);
                })

                var argShow = '(' + showArr.join(', ') + ')';
                this.setState({...this.state, argShow: argShow});
            });
        }

    }

    delFunction = () => {
        let that = this;
        confirm({
            title: '是否确定删除此方法?',
            content: '点击确定将删除此方法',
            onOk() {

                if(that.funId) {
                    let ret = delFunctionApi(that.funId)
                }

                that.props.onDelete()
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }

    onRef = (ref) => {
        this.controllerParams = ref
        console.info(' controller -function ref...')
    }

    showControllerParamsModal = () => {
        this.controllerParams.showModal();
        console.info('showControllerParamsModal.....cli');
    }

    render() {

        const formItemLayout = {
            labelCol: {
                sm: { span:  4},
            },
            wrapperCol: {
                sm: { span: 20 },
            },
        };

        const { getFieldDecorator } = this.props.form;
        const { funInfo } = this.state;
        return (
            <Card>
                <Form className="form_item_4" onSubmit={this.saveFuncInfo}>

                    <FormItem {...formItemLayout} label="方法名称" >
                        {getFieldDecorator('name', {
                            initialValue: funInfo.name,
                            rules: [{ required: true, message: 'Please input your name!' }],
                        })(
                            <Input className={"ant-col-12"} />

                        )}
                        <span className="ant-form-text"> 备注： 方法描述，如： 获取用户信息 </span>
                    </FormItem>

                    <FormItem {...formItemLayout} label="方法注释" >
                        {getFieldDecorator('comment', {
                            initialValue: funInfo.comment,
                            rules: [{ required: true, message: 'Please input your comment!' }],
                        })(
                            <TextArea className={"ant-col-12"} />
                        )}
                        <span className="ant-form-text"> 备注： 描述此方法的作用，和逻辑 </span>
                    </FormItem>

                    <FormItem {...formItemLayout} label="path" >
                        {getFieldDecorator('reqPath', {
                            initialValue: funInfo.reqPath,
                            rules: [{ required: true, message: 'Please input your comment!' }],
                        })(
                            <Input className={"ant-col-12"} />
                        )}
                        <span className="ant-form-text"> 备注： 访问地址如： /getUserInfo </span>
                    </FormItem>

                    <FormItem labelCol={{span:4}} wrapperCol={{span: 4}} label="method" >
                        {getFieldDecorator('reqMethod', {
                            initialValue: funInfo.reqMethod,
                            rules: [{ required: true, message: 'Please input your reqMethod!' }],
                        })(
                            <Select className={"ant-col-6"} placeholder="访问方式">
                                <Option value="GET">GET</Option>
                                <Option value="POST">POST</Option>
                                <Option value="PUT">PUT</Option>
                                <Option value="DELETE">DELETE</Option>
                                <Option value="HEAD">HEAD</Option>
                                <Option value="TRACE">TRACE</Option>
                                <Option value="OPTIONS">OPTIONS</Option>
                            </Select>
                        )}
                    </FormItem>

                    <FormItem {...formItemLayout} label="function name" >
                        {getFieldDecorator('funName', {
                            initialValue: funInfo.funName,
                            rules: [{ required: true, message: 'Please input your funName!' }],
                        })(
                            <Input className={"ant-col-12"} />
                        )}
                        <span className="ant-form-text"> 备注： 程序中的名称如 getUserInfo </span>
                    </FormItem>

                    <FormItem {...formItemLayout} label="return type" >
                        <Button type="primary" onClick={()=>{
                                this.props.doActionControllerFunReturnPopPanel('show', funInfo, (voShow)=>{
                                this.setState({returnShow:voShow})
                            })
                        }} className={"ant-col-6"}> {this.state.returnShow} </Button>
                        <span className="ant-form-text"> 备注： 返回的类型， 可以是 页面/对象， 范型对象 [ index.html 首页内容 ] </span>
                    </FormItem>

                    <FormItem {...formItemLayout} label="params" >
                        <Button type="primary" onClick={()=>{
                            if(funInfo.id) {
                                this.props.showControllerParams(funInfo, this.showParmas)
                            } else {
                                message.warning('请先保存方法，再添加参数！')
                            }
                        }} > {this.state.argShow != 'null' ? this.state.argShow : '()'} </Button>
                        <span className="ant-form-text"> 备注： 请求参数 </span>
                    </FormItem>

                    <FormItem {...formItemLayout} label=" ">
                        {getFieldDecorator('genService', {
                            initialValue: funInfo.genService,
                        })(
                            <Checkbox
                                checked={funInfo.genService == 'true' || funInfo.genService == true?true:false}
                                onChange={(val)=>{
                                    this.setState({...this.state, funInfo:{...funInfo, genService:val.target.checked}});
                                    console.info(`val=${val.target.checked}`);
                            }}>是否生成Service方法</Checkbox>
                        )}

                        <span className="ant-form-text"> 生成对应的service调用方法, 设置后不可修改</span>
                    </FormItem>

                    <FormItem {...formItemLayout} label=" ">
                        {getFieldDecorator('genClient', {
                            initialValue: funInfo.genClient,
                        })(
                            <Checkbox
                                checked={funInfo.genClient == 'true' || funInfo.genClient == true?true:false}
                                onChange={(val)=>{
                                    this.setState({...this.state, funInfo:{...funInfo, genClient:val.target.checked}});
                                    console.info(`val=${val.target.checked}`);
                                }}>是否生成微服务客户端 FeignClient</Checkbox>
                        )}

                        <span className="ant-form-text"> 生成对应的service调用方法, 设置后不可修改</span>
                    </FormItem>

                    <Button type="primary" style={{ marginRight: '3%' }} htmlType="submit" icon="save">save</Button>
                    <Button type="danger" onClick={this.delFunction} icon="delete">del function</Button>
                </Form>

            </Card>
        )
    }
}


const _ControllerFun = Form.create()(ControllerFun);
export default connect(state => ({...state.controllerFun}), action.controllerFun)(_ControllerFun)
